﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using CodeBuilder.Utility;

namespace CodeBuilder
{
    public partial class FormMain : Form
    {
        //string fileName = "log.txt";
        string lastFileFolder = "";
        public FormMain()
        {
            InitializeComponent();

            //InitConnection();
        }

        //private void InitConnection()
        //{

        //    try
        //    {
        //        if (File.Exists(fileName))
        //        {
        //            var file = System.IO.File.ReadAllLines(fileName, Encoding.Default);

        //            if (file.Length > 3)
        //            {
        //                txtDBSource.Text = file[0];
        //                txtDBName.Text = file[1];
        //                txtDBUser.Text = file[2];
        //                txtDBPassword.Text = file[3];
        //            }
        //        }
        //        else
        //        {
        //            File.WriteAllText(fileName, "");
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //        this.Close();
        //    }
        //}
        /// <summary>
        /// 链接数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDatabase_Click(object sender, EventArgs e)
        {
            try
            {
                listTable.Enabled = false;
                grpTable.Enabled = false;

                if (txtDBSource.Text.Length == 0)
                    throw new Exception("请输入数据库地址!");
                //else if (txtDBName.Text.Length == 0)
                //    throw new Exception("请输入要操作的表名!");
                //else if (txtDBUser.Text.Length == 0)
                //    throw new Exception("请输入数据库用户名!");
                //else if (txtDBPassword.Text.Length == 0)
                //    throw new Exception("请输入数据库密码!");

                //string[] result = System.IO.File.ReadAllLines(fileName, Encoding.Default);
                //if (result.Length > 3)
                //{
                //    result[0] = txtDBSource.Text;
                //    result[1] = txtDBName.Text;
                //    result[2] = txtDBUser.Text;
                //    result[3] = txtDBPassword.Text;
                //}
                //System.IO.File.WriteAllLines(fileName, result);
                SqlHelper.ConnectionString = txtDBSource.Text;
                Builder.NameSpace = txtNameSpace.Text;
                listTable.Items.Clear();
                foreach (var item in Database.GetTable())
                {
                    listTable.Items.Add(item);
                }

                listTable.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                listTable.Items.Clear();
                gridSource.Rows.Clear();
            }
        }


        private void btnClass_Click(object sender, EventArgs e)
        {
            new FormResult(Builder.buildClass(listTable.Text, (List<DataTableInfo>)listTable.Tag), lastFileFolder, listTable.Text).ShowDialog();
        }


        private void gridSource_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            gridSource.Rows.RemoveAt(e.RowIndex);
            var tableInfo = (List<DataTableInfo>)listTable.Tag;
            tableInfo.RemoveAt(e.RowIndex);
            listTable.Tag = tableInfo;
        }

        private void btnUnity_Click(object sender, EventArgs e)
        {
            string result = string.Format("\t.RegisterType<I{0}Service,{0}Service>(new HttpContextLifetimeManager<I{0}Service>())\r\n", listTable.Text);
            Clipboard.SetDataObject(result);
            MessageBox.Show("复制到剪贴板成功！");
        }

        private void btnInterface_Click(object sender, EventArgs e)
        {
            StringBuilder entityToModel = new StringBuilder();
            StringBuilder modelToEntity = new StringBuilder();

            foreach (DataGridViewRow item in gridSource.Rows)
            {
                try
                {
                    entityToModel.Append(string.Format("{0}=entity.{0},\r\n", item.Cells[0].Value.ToString()));
                    modelToEntity.Append(string.Format("entity.{0}=value.{0},\r\n", item.Cells[0].Value.ToString()));
                }
                catch
                {
                    continue;
                }
            }

            new FormResult(entityToModel.ToString() + System.Environment.NewLine + System.Environment.NewLine + modelToEntity.ToString()).ShowDialog();
        }

        private void listTable_SelectedIndexChanged(object sender, EventArgs e)
        {
            gridSource.Rows.Clear();
            gridPrimary.Rows.Clear();
            gridForeign.Rows.Clear();
            var tableInfo = Database.GetTableInfo(listTable.Text);
            foreach (var item in tableInfo)
            {
                gridSource.Rows.Add(item.ColumnName, item.Description, item.ColumnType, item.MappingResult.ConvertType,
                    item.IsPrimary, item.IsNullable, item.IsIdentity, item.MaxLength, item.Precision, item.Scale, item.DefaultValue);
            }
            listTable.Tag = tableInfo;

            grpTable.Enabled = true;

            //填充主键
            List<Relation> items = Database.GetRelation();
            foreach (var item in items.Where(s => s.PrimaryKeyTable == listTable.Text))
            {
                gridPrimary.Rows.Add(item.ForeignKeyTable, item.ForeignKey);
            }

            //填充外键
            foreach (var item in items.Where(s => s.ForeignKeyTable == listTable.Text))
            {
                gridForeign.Rows.Add(item.ForeignKey, item.PrimaryKeyTable);
            }
        }

        private void btnBatchClass_Click(object sender, EventArgs e)
        {
            //获取指定路径
            if (!string.IsNullOrEmpty(lastFileFolder))
            {
                folderBrowserDialog.SelectedPath = lastFileFolder;
            }
            folderBrowserDialog.Description = "请选择要导出的路径";
            folderBrowserDialog.ShowDialog();
            if (!string.IsNullOrEmpty(folderBrowserDialog.SelectedPath))
            {
                for (int i = 0; i < listTable.Items.Count; i++)
                {
                    System.IO.File.WriteAllText(Path.Combine(folderBrowserDialog.SelectedPath, listTable.Items[i].ToString() + ".cs"),
                        Builder.buildClass(listTable.Items[i].ToString(), Database.GetTableInfo(listTable.Items[i].ToString()))
                        );
                }
                MessageBox.Show("OK");
            }
        }

        private void btnListTemplate_Click(object sender, EventArgs e)
        {
            new FormResult(Builder.buildList(listTable.Text, (List<DataTableInfo>)listTable.Tag)).ShowDialog();
        }

        private void btnClassicEdit_Click(object sender, EventArgs e)
        {
            new FormResult(Builder.buildClassicEdit(listTable.Text, (List<DataTableInfo>)listTable.Tag)).ShowDialog();
        }

        private void btnWindowEdit_Click(object sender, EventArgs e)
        {
            new FormResult(Builder.buildWindEdit(listTable.Text, (List<DataTableInfo>)listTable.Tag)).ShowDialog();
        }

        private void btnAPICall_Click(object sender, EventArgs e)
        {
            new FormResult(string.Format(BuilderTemplate.BuildAPICallCode, listTable.Text)).ShowDialog();
        }

        private void btnController_Click(object sender, EventArgs e)
        {
            new FormResult(string.Format(BuilderTemplate.BuildControllerTemplate, listTable.Text, ((List<DataTableInfo>)listTable.Tag).FirstOrDefault(s => s.IsPrimary == true).MappingResult.ConvertType, lowerFirst(listTable.Text))).ShowDialog();
        }

        private void btnAPICode_Click(object sender, EventArgs e)
        {
            new FormResult(string.Format(BuilderTemplate.BuildAPICode, listTable.Text, ((List<DataTableInfo>)listTable.Tag).FirstOrDefault(s => s.IsPrimary == true).MappingResult.ConvertType, lowerFirst(listTable.Text))).ShowDialog();

        }

        private string lowerFirst(string str)
        {
            return str.Substring(0, 1).ToLower() + str.Substring(1, str.Length - 1);
        }

        private void btnTableInfo_Click(object sender, EventArgs e)
        {
            List<Relation> relations = Database.GetRelation();
            StringBuilder items = new StringBuilder();
            //获取指定路径
            if (!string.IsNullOrEmpty(lastFileFolder))
            {
                folderBrowserDialog.SelectedPath = lastFileFolder;
            }
            folderBrowserDialog.Description = "请选择要导出的路径";
            folderBrowserDialog.ShowDialog();
            if (!string.IsNullOrEmpty(folderBrowserDialog.SelectedPath))
            {
                for (int i = 0; i < listTable.Items.Count; i++)
                {
                    var table = Database.GetTableInfo(listTable.Items[i].ToString());

                    StringBuilder detail = new StringBuilder();
                    foreach (var item in table)
                    {
                        detail.Append("<tr><td>" + item.ColumnName + "</td><td>" + item.Description + "</td><td>" + item.ColumnType + "</td><td>" + item.IsPrimary + "</td><td>" + item.IsNullable + "</td><td>" + item.IsIdentity + "</td><td>" + item.MaxLength + "</td><td>" + item.Precision + "</td><td>" + item.Scale + "</td><td>" + item.DefaultValue + "</td></tr>");
                    }

                    items.Append(string.Format(BuilderTemplate.ExportDetail, listTable.Items[i].ToString(), detail.ToString()));

                    //填充主键
                    var relationPrimary = new StringBuilder();
                    foreach (var item in relations.Where(s => s.PrimaryKeyTable == listTable.Items[i].ToString()))
                    {
                        relationPrimary.Append(string.Format("<tr><td>{0}</td><td>{1}</td></tr>", item.ForeignKeyTable, item.ForeignKey));
                    }
                    if (relationPrimary.Length > 0)
                    {
                        items.Append(string.Format(BuilderTemplate.BuilRelationPrimaryTemplate, relationPrimary.ToString()));
                    }
                    var relationForeign = new StringBuilder();
                    //填充外键
                    foreach (var item in relations.Where(s => s.ForeignKeyTable == listTable.Items[i].ToString()))
                    {
                        relationForeign.Append(string.Format("<tr><td>{0}</td><td>{1}</td></tr>", item.ForeignKey, item.PrimaryKeyTable));
                    }
                    if (relationForeign.Length > 0)
                    {
                        items.Append(string.Format(BuilderTemplate.BuildRelationForeignTemplate, relationForeign.ToString()));
                    }

                }
                System.IO.File.WriteAllText(Path.Combine(folderBrowserDialog.SelectedPath, "result.html"), string.Format(BuilderTemplate.ExportMain, items.ToString()));
                MessageBox.Show("OK");
            }
        }

        private void gridSource_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                string name = gridSource.Rows[e.RowIndex].Cells[0].FormattedValue.ToString();
                string value = gridSource.Rows[e.RowIndex].Cells[1].FormattedValue.ToString();

                if (value == null || value.Trim().Length == 0) return;
                try
                {
                    SqlHelper.ExecteNonQuery(string.Format("EXEC sp_updateextendedproperty 'MS_Description','{0}','user',dbo,'TABLE','{1}','column','{2}'", value, listTable.Text, name));
                    MessageBox.Show("更新说明成功！");
                }
                catch
                {
                    try
                    {
                        SqlHelper.ExecteNonQuery(string.Format("EXECUTE sp_addextendedproperty N'MS_Description', '{0}', N'user', N'dbo', N'TABLE', N'{1}', N'column', N'{2}'", value, listTable.Text, name));
                        MessageBox.Show("更新说明成功！");
                    }
                    catch
                    {
                        MessageBox.Show("更新说明失败");
                    }
                }
            }
        }
    }
}
